package org.exussum0.eyecks1;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class DependencyAccumulator implements
		ClassFinder.Visitor,
		FsTraverser.Visitor {

	private Map<String, Set<String>> uses;
	private ClassFinder classFinder;
	private ClassResolver classResolver;
	private Set<Pattern> leftExcludes = Collections.emptySet();
	private Set<Pattern> rightExcludes = Collections.emptySet();

	public Set<Pattern> getLeftExcludes() {
		return leftExcludes;
	}

	public void setLeftExcludes(Set<Pattern> leftExcludes) {
		this.leftExcludes = leftExcludes;
	}

	public Set<Pattern> getRightExcludes() {
		return rightExcludes;
	}

	public void setRightExcludes(Set<Pattern> rightExcludes) {
		this.rightExcludes = rightExcludes;
	}

	public ClassResolver getClassResolver() {
		return classResolver;
	}

	public Map<String, Set<String>> getUses() {
		return uses;
	}

	public void setClassFinder(ClassFinder classFinder) {
		this.classFinder = classFinder;
	}

	public void setClassResolver(ClassResolver classResolver) {
		this.classResolver = classResolver;
	}

	public void setUses(Map<String, Set<String>> uses) {
		this.uses = uses;
	}

	public void visit(File file) throws Exception {
		if (file.isFile() && file.toString().endsWith(".java"))
			classFinder.find(file, this);
	}

	public void visit(String srcClass, String pkg, Collection<String> imports,
			String dstClass) throws Exception {
		// This covers a very odd bug.
		if ("".equals(srcClass))
			return;

		for (Pattern pattern : leftExcludes)
			if (pattern.matcher(srcClass).find())
				return;

		imports.add(pkg + ".*");
		imports.add("java.lang.*");
		dstClass = classResolver.resolve(imports, dstClass);

		if (dstClass == null || srcClass.equals(dstClass))
			return;
		for (Pattern pattern : rightExcludes)
			if (pattern.matcher(dstClass).find())
				return;

		Set<String> dependencies = uses.get(srcClass);
		if (dependencies == null) {
			dependencies = new HashSet<String>();
			uses.put(srcClass, dependencies);
		}
		dependencies.add(dstClass);
	}

}
